#!/bin/sh
#
# Requires netpbm, qt-faststart (part of ffmpeg), mjpegtools, x264 
# ...and an adequate $PATH to reach them

image_dir=$1
image_date=$2

cd ${image_dir} # This shouldn't matter, but find is being ridiculous

# We need these because x264 is dumb about input and output filetypes without
# an extension to hold its hand.
pipelineout="${image_dir}/${image_date}.X264_SHOULD_SUPPORT_PIPELINING_BETTER.mp4"

# Get the list of images to use in the timelapse and sort them
find "${image_dir}" -name "${image_date}"'-*.jpg' | sort | \
# Make a concatenated stream of all the images in order
xargs cat | \
# Convert the stream of JPEG images into a stream of PPM images
jpegtopnm -multiple -dct fast -nosmooth | \
# Convert the stream of PPM images into a YUV4MPEG2 (Y4M) movie stream
# TODO(wac): Experiment with ppmtoyuv here instead to eliminate x264 patch.
ppmtoy4m -I p -S 420mpeg2 | \
# Convert the Y4M movie stream into an H.264 movie file
x264 --y4m-input \
     --no-cabac \
     --ref 1 \
     --analyse all \
     --me umh \
     --subme 6 \
     --no-fast-pskip \
     --trellis 1 \
     --qp 26 \
     -o "${pipelineout}" \
     -

# Tweak the resulting H.264 MPEG4 movie to be able to start before it's fully
# loaded with QuickTime
# TODO(wac): Upstream fix to qt-faststart to support pipelining somehow.
qt-faststart "${pipelineout}" ${image_dir}/${image_date}.mp4

# Remove the temporary file we used.
rm ${pipelineout} 

